package userDao

import (
	"fmt"
	user "gin/domain"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

func main() {
	//u1:=user.Tb_user{
	//	Name: "小照",
	//	Pwd:  "202cb962ac59075b964b07152d234b70",
	//	Sex:  "男",
	//	Home: "",
	//}
	//u2:=user.Tb_user{
	//	Home: "上海",
	//}
	//Modify(u1,u2)
}

//数据库加载，这里没写好，写急了，没考虑到数据库开关多次影响性能，也没考虑到多用户访问时线程问题
func dbLoad() *gorm.DB {
	db, err := gorm.Open("mysql", "root:A123456@(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local")
	db.AutoMigrate(&user.Tb_user{})
	if err != nil {
		panic(err)
	}
	return db
}

//用户登录
func Login(name string, pwd string) user.Tb_user {
	db := dbLoad()
	defer db.Close()
	db.SingularTable(true)
	var u1 user.Tb_user
	db.Find(&u1, "name=? and pwd=?", name, pwd)
	return u1
}

//用户列表拉取
func GetUserList() []user.Tb_user {
	var users []user.Tb_user
	db := dbLoad()
	defer db.Close()
	db.SingularTable(true)
	err := db.Find(&users).Error
	if err != nil {
		panic(err)
	}
	return users
}

//注册
func Register(user user.Tb_user) bool {
	db := dbLoad()
	defer db.Close()
	db.SingularTable(true)
	err := db.Create(&user).Error
	if err != nil {
		panic(err)
	}
	return true
}

//删除
func Delete(user user.Tb_user) bool {
	db := dbLoad()
	defer db.Close()
	db.SingularTable(true)
	fmt.Println("-----------")
	fmt.Println(user)
	err := db.Where("id=?", user.Id).Delete(user)
	if err != nil {
		return false
	}
	return true
}

//管理员登录
func Admin(name string, pwd string) user.Tb_admin {
	db := dbLoad()
	defer db.Close()
	db.SingularTable(true)
	var admin user.Tb_admin
	db.Find(&admin, "name=? and pwd=?", name, pwd)
	return admin
}

//修改
func Modify(user user.Tb_user, newForm user.Tb_user) (bool, user.Tb_user) {
	db := dbLoad()
	defer db.Close()
	db.SingularTable(true)
	err := db.Model(&user).Where(user).Update(newForm)
	if err != nil {
		return false, user
	}
	db.Where("name=? and pwd=?", user.Name, user.Pwd).First(&user)
	return true, user
}
func AdModify(user user.Tb_user, newForm user.Tb_user) bool {
	db := dbLoad()
	defer db.Close()
	db.SingularTable(true)
	err := db.Model(&user).Where(user).Update(newForm)
	if err != nil {
		panic(err)
		return false
	}
	return true
}
